from django.shortcuts import render
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
from accounts.models import User, Technician
from orders.models import Order
from .models import AdminLog
from .serializers import AdminLogSerializer


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def admin_dashboard(request):
    if request.user.role != 'admin':
        return Response({'error': '无权访问'}, status=status.HTTP_403_FORBIDDEN)

    # 获取统计数据
    total_users = User.objects.count()
    total_technicians = Technician.objects.count()
    total_orders = Order.objects.count()
    completed_orders = Order.objects.filter(status='completed').count()

    data = {
        'total_users': total_users,
        'total_technicians': total_technicians,
        'total_orders': total_orders,
        'completed_orders': completed_orders,
        'completion_rate': round(completed_orders / total_orders * 100, 2) if total_orders > 0 else 0
    }

    return Response(data)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def technician_list(request):
    if request.user.role != 'admin':
        return Response({'error': '无权访问'}, status=status.HTTP_403_FORBIDDEN)

    # 获取待审核的技师
    technicians = Technician.objects.filter(is_verified=False)

    # 简化数据返回
    data = []
    for tech in technicians:
        data.append({
            'id': tech.id,
            'real_name': tech.real_name,
            'id_card': tech.id_card,
            'id_card_front': tech.id_card_front,
            'id_card_back': tech.id_card_back,
            'certification': tech.certification,
            'service_area': tech.service_area,
            'experience': tech.experience,
            'user_id': tech.user.id,
            'username': tech.user.username,
            'phone': tech.user.phone,
            'avatar': tech.user.avatar
        })

    return Response(data)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def approve_technician(request, technician_id):
    if request.user.role != 'admin':
        return Response({'error': '无权访问'}, status=status.HTTP_403_FORBIDDEN)

    try:
        technician = Technician.objects.get(id=technician_id, is_verified=False)
    except Technician.DoesNotExist:
        return Response({'error': '技师不存在或已审核'}, status=status.HTTP_404_NOT_FOUND)

    # 更新技师状态
    technician.is_verified = True
    technician.save()

    # 更新用户角色
    technician.user.role = 'technician'
    technician.user.save()

    # 记录操作日志
    AdminLog.objects.create(
        admin_user=request.user,
        action='approve',
        model_name='Technician',
        object_id=technician.id,
        description=f'审核通过技师 {technician.real_name}',
        ip_address=request.META.get('REMOTE_ADDR')
    )

    return Response({'message': '审核通过'})


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def reject_technician(request, technician_id):
    if request.user.role != 'admin':
        return Response({'error': '无权访问'}, status=status.HTTP_403_FORBIDDEN)

    try:
        technician = Technician.objects.get(id=technician_id, is_verified=False)
    except Technician.DoesNotExist:
        return Response({'error': '技师不存在或已审核'}, status=status.HTTP_404_NOT_FOUND)

    # 记录操作日志
    AdminLog.objects.create(
        admin_user=request.user,
        action='reject',
        model_name='Technician',
        object_id=technician.id,
        description=f'拒绝技师 {technician.real_name}，原因：{request.data.get("reason", "未提供")}',
        ip_address=request.META.get('REMOTE_ADDR')
    )

    # 删除技师记录
    technician.delete()

    return Response({'message': '已拒绝'})


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def order_list(request):
    if request.user.role != 'admin':
        return Response({'error': '无权访问'}, status=status.HTTP_403_FORBIDDEN)

    # 获取所有订单
    orders = Order.objects.all().order_by('-created_at')

    # 简化数据返回
    data = []
    for order in orders:
        data.append({
            'id': order.id,
            'customer': order.customer.username,
            'technician': order.technician.real_name,
            'service': order.service.name,
            'status': order.get_status_display(),
            'final_price': str(order.final_price),
            'appointment_time': order.appointment_time,
            'created_at': order.created_at
        })

    return Response(data)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def admin_logs(request):
    if request.user.role != 'admin':
        return Response({'error': '无权访问'}, status=status.HTTP_403_FORBIDDEN)

    # 获取操作日志
    logs = AdminLog.objects.all().order_by('-created_at')[:100]  # 限制100条
    serializer = AdminLogSerializer(logs, many=True)
    return Response(serializer.data)
